import axios from "axios";
import { ElMessage } from "element-plus";

/**
 * @description 创建axios实例
 */
const service = axios.create({
  baseURL: "/api",
  timeout: 15000, // 默认超时时间设置为5秒
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  },
});

/**
 * @description 请求拦截器
 */
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 不需要验证的接口
const noAuthList = [
  "/vuln_db/vuln_export/", // 导出漏洞信息
  "/api/user/auth", // 登录
];

/**
 * @description 响应拦截器
 */
service.interceptors.response.use(
  (response) => {
    const data = response.data;
    // 二进制数据
    if (data instanceof Blob) {
      return response;
    }
    // 文件下载
    if (response.headers["content-type"] == "application/octet-stream") {
      return data;
    }
    // 请求成功
    if (data.code === 200) {
      return data;
    } else if (noAuthList.includes(response.config.url)) {
      return data;
    } 
    else if (data.code === 431) { // 431 为未登录，或者登陆过期
      // window.location.href = data.data
    } 
    else {
      ElMessage.error(data?.msg ||data?.data || "响应报错");
      // localStorage.removeItem('token')
      // router.push('/login')
      return Promise.reject(new Error(data?.msg ||data?.data || "响应报错"));
    }
  },
  (error) => {
    console.log('error', error)
    const { response } = error;
    let errorMsg = "请求失败";

    if (response) {
      // 根据不同的HTTP状态码处理不同的错误
      switch (response.status) {
        case 400:
          errorMsg = "请求错误(400)";
          break;
        case 401:
          errorMsg = "未授权，请重新登录(401)";
          // 清除token并跳转登录页
          // localStorage.removeItem("token");
          // router.push("/login");
          break;
        case 403:
          errorMsg = "拒绝访问(403)";
          break;
        case 404:
          errorMsg = "请求出错(404)";
          break;
        case 408:
          errorMsg = "请求超时(408)";
          break;
        case 500:
          errorMsg = "服务器错误(500)";
          break;
        case 501:
          errorMsg = "服务未实现(501)";
          break;
        case 502:
          errorMsg = "网络错误(502)";
          break;
        case 503:
          errorMsg = "服务不可用(503)";
          break;
        case 504:
          errorMsg = "网络超时(504)";
          break;
        default:
          errorMsg = `连接出错(${response.status})!`;
      }
    } else {
      // 请求超时或者网络有问题
      if (error.message.includes("timeout")) {
        errorMsg = "请求超时！";
      }
      if (error.message.includes("Network Error")) {
        errorMsg = "网络异常，请检查网络连接！";
      }
    }

    ElMessage.error(errorMsg);
    return Promise.reject(error);
  }
);

export default service;
